//
//  MainViewController.m
//  LvXingPai
//
//  Created by mafang on 16/8/10.
//  Copyright © 2016年 _Junxee. All rights reserved.
//

#import "MainViewController.h"

// 首页cell
#import "MainCell.h"
#import "SaleModel.h"

// 表头中部滚动视图数据
#import "MidModel.h"

// 跳转
#import "WebViewController.h"
#import "MidWebViewController.h"

@interface MainViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIScrollView *topScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *midScrollView;

// '特价折扣' 数据源
@property (nonatomic,strong) NSMutableArray *saleArray;
// '小编推荐' 数据源
@property (nonatomic,strong) NSMutableArray *recomdArray;

// 顶部滚动视图接收数组
@property (nonatomic,strong) NSMutableArray *topArray;

// 中间滚动视图接收数组
@property (nonatomic,strong) NSMutableArray *midArray;

@property (nonatomic,strong) UIPageControl *pageControl;

@end

@implementation MainViewController

#pragma mark - 懒加载
- (NSMutableArray *)saleArray
{
    if (_saleArray == nil) {
        _saleArray = [NSMutableArray array];
    }
    return _saleArray;
}

- (NSMutableArray *)topArray
{
    if (_topArray == nil) {
        _topArray = [NSMutableArray array];
    }
    return _topArray;
}

- (NSMutableArray *)midArray
{
    if (_midArray == nil) {
        _midArray = [NSMutableArray array];
    }
    return _midArray;
}

- (NSMutableArray *)recomdArray
{
    if (_recomdArray == nil) {
        _recomdArray = [NSMutableArray array];
    }
    return _recomdArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //设置状态栏不占界面控件
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    //改变状态栏样式
    [self preferredStatusBarStyle];
    // 获取网络数据
    [self createData];
    [self downloadData];
    
    // 添加手势
    [self addTap];
}

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //隐藏导航栏
    self.navigationController.navigationBarHidden = YES;
}

#pragma mark - 创建表头框架
- (void)createHeader
{
    // 顶部滚动视图
    for (int i = 0; i<self.topArray.count; i++) {
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_W *(i+1), 0, SCREEN_W, self.topScrollView.bounds.size.height)];
        [imageView sd_setImageWithURL:[NSURL URLWithString:self.topArray[i]] placeholderImage:[UIImage imageNamed:@"master_placeholder_bg"]];
        [self.topScrollView addSubview:imageView];
    }
    
    // 在最前面添加冗余的最后一张图片
    UIImageView *view1 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, self.topScrollView.bounds.size.height)];
    view1.image = [UIImage imageNamed:self.topArray[self.topArray.count-1]];
    [self.topScrollView addSubview:view1];
    
    // 在最后面添加第一张图片
    UIImageView *view2 = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_W * 5, 0, SCREEN_W, self.topScrollView.bounds.size.height)];
    view2.image = [UIImage imageNamed:self.topArray[0]];
    [self.topScrollView addSubview:view2];
    
    // 设置scrollView的移动范围
    self.topScrollView.contentSize = CGSizeMake(SCREEN_W *(self.topArray.count+2), 0);
    
    //  偏移到真正第一张的位置
    self.topScrollView.contentOffset = CGPointMake(SCREEN_W, 0);
    
    //  处理scrollView
    self.topScrollView.showsHorizontalScrollIndicator = NO;
    self.topScrollView.bounces = NO;
    
    // 设置scrollView为翻页状态
    self.topScrollView.pagingEnabled = YES;
    
    // 添加分页控件
    self.pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(SCREEN_W/3.0, 170, SCREEN_W/3.0, 50)];
    [self.tableView.tableHeaderView addSubview:self.pageControl];
    
    self.pageControl.numberOfPages = self.topArray.count;
    // 设置当前页数
    self.pageControl.currentPage = 0;
    
    // 添加定时器
    [NSTimer scheduledTimerWithTimeInterval:5.5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    
    
    
    // 中间滚动视图
    for (int i = 0; i<self.midArray.count; i++) {
         UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake((100 + 10)*i + 10, 10, 100, 100)];
        
        MidModel *model = self.midArray[i];
        [imageView sd_setImageWithURL:[NSURL URLWithString:model.urlStr] placeholderImage:[UIImage imageNamed:@"master_placeholder_bg"]];
        
        [self.midScrollView addSubview:imageView];
        
        // 打开人机交互
        imageView.userInteractionEnabled = YES;
        
        // 给中间滚动视图添加手势
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction2:)];
        [imageView addGestureRecognizer:tap2];
    }
    
    //  处理scrollView
    self.midScrollView.showsHorizontalScrollIndicator = NO;
    self.midScrollView.bounces = NO;
    
    // 设置scrollView的移动范围
    self.midScrollView.contentSize = CGSizeMake((100 + 10) *self.midArray.count + 10 , self.midScrollView.bounds.size.height);
}

#pragma mark - 给顶部滚动视图添加手势
- (void)addTap
{
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction1:)];
    [self.topScrollView addGestureRecognizer:tap1];
}

#pragma mark - 点击顶部滚动视图所触发的事件

- (void)tapAction1:(UITapGestureRecognizer *)tap
{
    WebViewController *webVC = [[WebViewController alloc]init];
    
    // 得到点击的是哪个顶部视图
    if (self.topScrollView.contentOffset.x/SCREEN_W != 1 && self.topScrollView.contentOffset.x/SCREEN_W !=2) {
        
        if (self.topScrollView.contentOffset.x/SCREEN_W == 3){
            webVC.urlStr = @"http://h5.lvxingpai.com/market/cglx.html";
        } else {
            webVC.urlStr = @"http://h5.lvxingpai.com/biye/graduation.html";
        }
        [self.navigationController pushViewController:webVC animated:YES];
        
    } else {
        [self idAction:nil];
    }
}

#pragma mark - 点击中间滚动视图所触发的事件

- (void)tapAction2:(UITapGestureRecognizer *)tap
{
    UIImageView *imageView = (UIImageView *)tap.view;
    
    NSInteger count = imageView.frame.origin.x/(100+10);
    
    MidModel *model = self.midArray[count];
    
    MidWebViewController *midVC = [[MidWebViewController alloc]init];
    
    // 传值
    midVC.urlStr = model.linkStr;
    
    midVC.title = model.title;
    
    [self.navigationController pushViewController:midVC animated:YES];
}

#pragma mark - StoryBoard界面通过Segue跳转触发的事件
- (IBAction)idAction:(id)sender
{
    if (self.topScrollView.contentOffset.x/SCREEN_W == 1) {
        [self performSegueWithIdentifier:@"segueID" sender:@"103286"];
    }
    if (self.topScrollView.contentOffset.x/SCREEN_W == 2) {
        [self performSegueWithIdentifier:@"segueID" sender:@"103254"];
    }
}


#pragma mark - 连线之间界面跳转之前所触发的事件(传值)
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    [segue.destinationViewController setValue:sender forKey:@"commodityId"];
}

#pragma mark - 定时器循环事件
-(void)timerAction {
    
    CGPoint point = self.topScrollView.contentOffset;
    
    //    让scrollView偏移一个单位
    point.x += SCREEN_W;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.topScrollView.contentOffset = point;
    }];
    
    NSInteger pageNum = point.x/SCREEN_W;
    
    self.pageControl.currentPage = pageNum-1;
    
    if (pageNum == 0) {
        self.topScrollView.contentOffset = CGPointMake(SCREEN_W*self.topArray.count, 0);
        self.pageControl.currentPage = 4;
        return;
    }
    
    if (pageNum == 5) {
        self.topScrollView.contentOffset = CGPointMake(SCREEN_W*1, 0);  //由于前面已经有了一张冗余的图片
        self.pageControl.currentPage = 0;
        return;
    }
}

#pragma mark - 顶部滚动视图停止减速时触发
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if (![scrollView isKindOfClass:[UITableView class]]) {
        
        CGPoint point = scrollView.contentOffset;
        NSInteger pageNum = point.x/SCREEN_W;
        self.pageControl.currentPage = pageNum-1;
        
        //    滚动到真正的最后一页
        if (pageNum == 0) {
            //        设置不带动画的偏移设置    （带动画的是用set contentOffset）
            scrollView.contentOffset = CGPointMake(self.topArray.count*SCREEN_W, 0);
            self.pageControl.currentPage = 3; //分页控件设置为最后一页
            return;
        }
        //    滚动到真正的第一页
        if (pageNum == 5) {
            scrollView.contentOffset = CGPointMake(SCREEN_W, 0);
            self.pageControl.currentPage = 0;  //分页控件设置为第一页
            return;
        }
    }
}

#pragma mark - 获取滚动视图的数据
- (void)createData
{
    __weak typeof(self) weakSelf = self;
    
    NSURL *url = [NSURL URLWithString:@"http://api.lvxingpai.com/app/columns"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"请求数据失败,error==%@",error);
        } else {
            NSLog(@"请求成功");
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = dict[@"result"];
            
            // 顶部scroll数据的获取
            NSDictionary *dic1 = array[0];
            NSArray *arr1 = dic1[@"columns"];
            for (NSDictionary *d1 in arr1) {
                
                NSArray *a1 = d1[@"images"];
                NSDictionary *dt1 = a1[0];
                [self.topArray addObject:dt1[@"url"]];
            }
            
            // 中间scroll数据的获取
            NSDictionary *dic2 = array[1];
            NSArray *arr2 = dic2[@"columns"];
            for (NSDictionary *d2 in arr2) {
                
                MidModel *model = [[MidModel alloc]initWithDict:d2];
                [self.midArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf createHeader];
            });
        }
    }];
    [task resume];
}


#pragma mark - 获取首页cell的网络数据
- (void)downloadData
{
    __weak typeof(self) weakSelf = self;
    
    NSURL *url = [NSURL URLWithString:@"http://api.lvxingpai.com/app/marketplace/commodities/recommendations"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error) {
            NSLog(@"数据失败,error==%@",error);
        } else {
            
            NSLog(@"获取数据成功");
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = dict[@"result"];
            
            // 特价折扣
            NSDictionary *d1 = array[0];
            NSArray *arr1 = d1[@"commodities"];
            for (NSDictionary *dic1 in arr1) {
                SaleModel *saleModel1 = [[SaleModel alloc]initWithDict:dic1];
                [self.saleArray addObject:saleModel1];
            }
            
            // 小编推荐
            NSDictionary *d2 = array[1];
            NSArray *arr2 = d2[@"commodities"];
            for (NSDictionary *dic2 in arr2) {
                SaleModel *saleModel2 = [[SaleModel alloc]initWithDict:dic2];
                [self.recomdArray addObject:saleModel2];
            }
            // 回到主线程并刷新表格视图
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
            });
        }
    }];
    [task resume];
}

#pragma mark - UITableViewDelegate 点击cell跳转事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 通过详情界面 StoryBoard的Id 来直接跳转
    DetailViewController *detailVC = [self.storyboard instantiateViewControllerWithIdentifier:@"detailID"];
    
    if (indexPath.section == 0) {
        SaleModel *model = self.saleArray[indexPath.row];
        detailVC.commodityId = model.commodityId;
    } else {
        SaleModel *model = self.recomdArray[indexPath.row];
        detailVC.commodityId = model.commodityId;
    }
    
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1) {
        return self.recomdArray.count;
    } else {
        return self.saleArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MainCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];
    
    if (indexPath.section == 1) {
        cell.saleModel = self.recomdArray[indexPath.row];
    } else {
        cell.saleModel = self.saleArray[indexPath.row];
    }
    return cell;
}

// 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 230;
}

// 段落标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return @"小编推荐";
    } else {
        return @"特价折扣";
    }
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
